const sqlConn1715 = require('../utils/sqlserver1715');

const ledMessage = async (req, res) => {
  try {  
    // 避免使用SELECT * 导致查询包含不支持字符集的列
    let sqlstr = "";
    const ConverterNumber = req.body.ConverterNumber;
    if(ConverterNumber=='6')
      sqlstr = "SELECT COMM_NR,ITEM_NAME,AFTER_RO,TEST_DATE FROM LIMS_SMELT_ITEM WHERE COMM_NR in (select COMM_NR from (SELECT * FROM LIMS_SMELT_ITEM ORDER BY SID DESC)  where REGEXP_LIKE(COMM_NR, '^(BP|CP)[0-9]{2}6[^9].*$') and AFTER_RO is not Null and rownum<=1)";
    else if(ConverterNumber=='5')
      sqlstr = "SELECT COMM_NR,ITEM_NAME,AFTER_RO,TEST_DATE FROM LIMS_SMELT_ITEM WHERE COMM_NR in (select COMM_NR from (SELECT * FROM LIMS_SMELT_ITEM ORDER BY SID DESC)  where REGEXP_LIKE(COMM_NR, '^(BP|CP)[0-9]{2}5[^9].*$') and AFTER_RO is not Null and rownum<=1)";
    else if(ConverterNumber=='2')
      sqlstr = "select COMM_NR,ITEM_NAME,AFTER_RO,TEST_DATE from LIMS_SMELT_ITEM where COMM_NR= (select COMM_NR from (SELECT * FROM LIMS_SMELT_ITEM ORDER BY SID DESC)  where REGEXP_LIKE(COMM_NR, '^(BP|CP)[0-9]{2}69.*$') and AFTER_RO is not Null and rownum<=1)";
    else if(ConverterNumber=='1')
      sqlstr = "select COMM_NR,ITEM_NAME,AFTER_RO,TEST_DATE from LIMS_SMELT_ITEM where COMM_NR= (select COMM_NR from (SELECT * FROM LIMS_SMELT_ITEM ORDER BY SID DESC)  where REGEXP_LIKE(COMM_NR, '^(BP|CP)[0-9]{2}58.*$') and AFTER_RO is not Null and rownum<=1)";
    else
      sqlstr = "SELECT COMM_NR,ITEM_NAME,AFTER_RO,TEST_DATE FROM LIMS_SMELT_ITEM WHERE COMM_NR in (select COMM_NR from (SELECT * FROM LIMS_SMELT_ITEM ORDER BY SID DESC)  where REGEXP_LIKE(COMM_NR, '^(BP|CP)[0-9]{2}5[^9].*$') and AFTER_RO is not Null and rownum<=1)";
    const result = await sqlConn1715(sqlstr);
    // 安全检查   
    if (result && result.rows && result.rows.length > 0) {
      res.send({
        code: 200,
        message: '数据获取成功!',
        data: result.rows,
        total: result.rows.length
      });
    } else {
      res.send({
        code: 200,
        message: '查询成功，但未找到数据',
        data: [],
        total: 0
      });
    }
  } catch (error) {
    // 捕获并处理所有错误
    console.error("API处理错误:", error);
    
    // 特别处理字符集错误
    if (error.code === 'NJS-100' && error.message.includes('character set')) {
      return res.status(500).send({
        code: 500,
        message: '数据库字符集不兼容，请尝试只查询数字类型的列',
        error: error.message
      });
    }
    
    res.status(500).send({
      code: 500,
      message: '数据获取失败!',
      error: error.message || String(error)
    });
  }
};

module.exports = {
  ledMessage
};